const db = require("../db/util");
const bcrypt = require("bcryptjs");

let  getUserInfo = (req,res) => {
  let sql = "select id, username, nickname, email, user_pic from ev_users where id=?"

  db.query(sql,req.user.id,(err,results) => {

    if(err) return res.cc(err.message);

    if (results.length == 0) return res.cc("获取信息失败")

    res.send({
      status: 0,
      message: '获取用户基本信息成功！',
      data: results[0],
    })

  })
}


let updataUserInfo = (req, res, next) => {

  const sql = "select * from ev_users where id=?"
  db.query(sql,req.body.id,(err,results) => {
    if(err) return res.cc(err.message);

    if(results.length == 0) return res.cc("用户不存在")

    const sql = `update ev_users set ? where id=?`;

    db.query(sql, [req.body, req.body.id], (err, results) => {
      if (err) return res.cc(err.message);
  
      if (results.length == 0) return res.cc("更新失败");
  
      res.cc("更新成功", 0);
    });
  })


};

let updatapwd = (req, res, next) => {
  //判断用户是否存在
  const sql = "select * from ev_users where id=?";
  
  db.query(sql, req.user.id, (err, results) => {
    if (err) return res.cc(err.message);
    if (results.length == 0) return res.cc("账户不存在");

    const flag = bcrypt.compareSync(req.body.oldPwd, results[0].password);

    if (!flag) return res.cc("密码错误");
    req.body.newPwd = bcrypt.hashSync(req.body.newPwd, 10);
    const sql = "update ev_users set password=? where id=?";
    
    db.query(sql, [req.body.newPwd, req.user.id], (err, results) => {
      if (err) return res.cc(err.message);

      if (results.affectedRows == 0) return res.cc("更新失败");

      res.cc("更新成功", 0);
    });
  });
};

//更换头像
let updataAvatar = (req,res)=>{
  const sql = "update ev_users set user_pic=? where id=?"
  db.query(sql,[req.body.avatar,req.user.id],(err,results) => {
    if(err) return res.cc(err.message)

    if(results.affectedRows == 0) return res.cc('头像更新失败')

    res.cc("更新成功",0)
  })
}

module.exports = {
  getUserInfo,
  updataUserInfo,
  updataAvatar,
  updatapwd
}
